package com.coded2.infra.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import org.richfaces.json.JSONException;
import org.richfaces.json.JSONObject;

public class BuscaPorCep {

	public static String buscaEnderecoPorCep(String cep)
			throws MalformedURLException, IOException, ProtocolException,
			JSONException {
		try{
			String request = "http://cep.republicavirtual.com.br/web_cep.php?cep="+cep+"&formato=json";
			URL url = new URL(request); 
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();           
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setInstanceFollowRedirects(false); 
			connection.setRequestMethod("POST"); 
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
			connection.setRequestProperty("charset", "utf-8");
			connection.setUseCaches (false);
			connection.setConnectTimeout(30000);
			
			BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			StringBuilder sb = new StringBuilder();
			String line;
			while ((line = br.readLine()) != null) {
				sb.append(line+"\n");
			}
			connection.disconnect();
			JSONObject json = new JSONObject(sb.toString());
			String retorno = null;
			if("1".equals(json.getString("resultado"))){
				retorno = json.getString("tipo_logradouro")+" ";
				retorno += json.getString("logradouro")+"\n";
				retorno += json.getString("bairro")+"\n";
				retorno += json.getString("cidade")+"\n";
			}
				
			return retorno;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		
	}
}
